# -*- coding: utf-8 -*-
# 
# 该文件主要用于合并excel表
# 
import sys, os, glob
from xlrd import open_workbook
import xlwt, time

# 设置标题
stitles=[
        u"姓名",
        u"部门",
        u"室别",
        u"二级项目",
        u"一级项目",
        u"工时比",
        u"项目成果",
        u"初评负责人",
        u"初评绩效",
        u"部门认定",
        ]

# 设置宽度
swidths=[
        0x1800,
        0x1400,
        0x1400,
        0x1400,
        0x1400,
        0x1400,
        0x1400,
        0x1400,
        0x1400,
        0x1400,
        ]

try:
    sys.path.insert(0, "..")
    from mgconfig import *
except Exception, e:
    sheet_prefix='2015'
    START_LINE=3    # 从哪一行开始判断
    JUDGE_COL=8        # 判断哪一列非空
    MAX_LINE=50        # 一张sheet最大判断多少行
    START_COL=0        # 复制的起始列
    END_COL=10        # 复制的最终列

def write_line(s, line, values):
    for i in range(len(values)):
        s.write(line, i, values[i])
    return line+1

def set_sheet_format(sheet, titiles=[], widths=[]):
    if isinstance(widths, list):
        for i in range(len(widths)):
            sheet.col(i).width = widths[i]

    line = 0
    if len(titiles) > 0:
        line = write_line(sheet, 0, titiles)
    #sheet.col(NDEP_INDEX  ).width = 0x1000
    #sheet.col(NWEEK_INDEX ).width = 0x0400
    #sheet.col(NPNAME_INDEX).width = 0x2000
    #sheet.col(NPTIME_INDEX).width = 0x0400
    #sheet.col(NPJOB_INDEX ).width = 0x3000
    return line

def read_workbook(filename, judge_col =JUDGE_COL, start_line=START_LINE, max_line=MAX_LINE, start_col=START_COL, end_col=END_COL):
    """
     @param judge_col   判断用于判断的列
     @param start_line  判断的起始行
     @param start_col   复制的起点列
     @param end_col     复制的终点列
    """
    ret = []
    wb = open_workbook(filename)   
      
    for s in wb.sheets():   
        if sheet_prefix == '' or s.name.startswith(sheet_prefix):
            #print s.name.encode('GBK'), "Rows", s.nrows
            end_line = min(s.nrows, max_line)
            for line in range(start_line, end_line):
                judge_cell  = s.cell(line, judge_col).value
                if isinstance(judge_cell, str) or isinstance(judge_cell, unicode):
                    value = judge_cell.encode('GBK').strip()
                else:
                    value = judge_cell
                #print "line ", line, value
                if value != "":
                    print "==="
                    line_contect = []
                    for row in range(start_col, end_col):
                        real_cell = s.cell(line, row).value
                        #.encode('GBK')
                        line_contect.append(real_cell)
                        if isinstance(real_cell, unicode):
                            print real_cell.encode('GBK')
                        else:
                            print real_cell,
                    print "==="
                    ret.append(line_contect)
    return ret

def write_workbook(result, filename=""):
    if filename=="":
        filename = time.strftime("AutoMerged%Y%m%d%H%M%S.xls",time.localtime())
    nwb = xlwt.Workbook()
    sheet = nwb.add_sheet('2015Result')
    line = set_sheet_format(sheet, stitles, swidths)

    for item in result:
        line = write_line(sheet, line, item)
    nwb.save(filename)

def read_wbs_and_write(input_files, output_file, judge_col =JUDGE_COL, start_line=START_LINE, max_line=MAX_LINE, start_col=START_COL, end_col=END_COL):
    ret = []
    for sfile in input_files:
        print "==Reading", sfile
        items = read_workbook(sfile, judge_col, start_line, max_line, start_col, end_col)
        ret.extend(items)
    #print(ret)
    write_workbook(ret, output_file)

def read_dir_and_write(dnames, judge_col):
    for sdir in dnames:
        sheets = glob.glob(sdir+'/*.xls*')
        print "====Reading", sdir
        if len(sheets) > 0:
            read_wbs_and_write(sheets, sdir+time.strftime("_%Y%m%d%H%M%S.xls",time.localtime()), judge_col)

if __name__ == '__main__':
    #read_workbook('abc.xls', int(sys.argv[1]))
    #read_wbs_and_write(sys.argv[1:])
    col = JUDGE_COL
    start = 1
    if sys.argv[1] == '-d':
        col = int(sys.argv[2])
        start = 3
    read_dir_and_write(sys.argv[start:], col)
